import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { InputC, PrimaryC, FormGroup, DATA_ENTRY, TableC, ModalC } from '../../../../comps';
import debounce from 'lodash/debounce';
import moment from 'moment';
import CardC from '../comps/cardC';
import styles from './index.less';
import search from '../../../../assets/busi/workStation/Barra/search.png';
import url from '../../../../assets/busi/workStation/Barra/product_bg.png';
import pic from '../../../../assets/busi/workStation/Barra/noProduct.png';
import _ from 'lodash';
@connect(({ loading, workStationM, barraProductM }) => ({
  loading,
  workStationM,
  barraProductM,
}))
@Form.create()
export default class ProductComp extends PureComponent {
  constructor() {
    super();
    this.state = {
      state: 1,
      activeIndex: undefined, // 表格高亮行
      columns: [
        {
          key: 'portfolioType',
          dataIndex: 'portfolioType',
          type: 'filterCol',
          title: '组合类型',
          width: 120,
          filters: [
            {
              text: '真实',
              value: '1',
            },
            {
              text: '模拟',
              value: '2',
            },
          ],
          onFilter: (value, record) => record.portfolioType.indexOf(value) === 0,
          render: (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              let temp = [
                {
                  text: '真实',
                  value: '1',
                },
                {
                  text: '模拟',
                  value: '2',
                },
              ].filter((ele) => {
                return ele.value === text;
              });
              return temp && temp.length ? temp[0].text : '--';
            }
          },
        },
        {
          key: 'portfolioCode',
          dataIndex: 'portfolioCode',
          // width: 120,
          title: '组合代码',
          render: (text, record) => {
            if (text) {
              if (record.portfolioType === '1') {
                return text;
              }
            } else {
              return '--';
            }
          },
        },
        {
          key: 'portfolioName',
          dataIndex: 'portfolioName',
          title: '组合名称',
          render: (text, record) => {
            if (text) {
              return <a onClick={() => this.selectRow(record, record.portfolioCode)}>{text}</a>;
            } else {
              return '--';
            }
          },
        },
        {
          key: 'benchName',
          dataIndex: 'benchName',
          title: '业绩基准',
          width: 150,
        },
        {
          key: 'establishTime',
          dataIndex: 'establishTime',
          title: '成立日',
          type: 'date',
        },
        {
          key: 'endDate',
          dataIndex: 'endDate',
          title: '到期日',
          type: 'date',
        },
        {
          key: 'createTime',
          dataIndex: 'createTime',
          title: '创建日',
          type: 'date',
        },
      ],
      dataSource: [],
      portfolioList: [],
      showContent: true, // 是否展开
      showModal: false, //模拟组合模态框
      productNum: 0, //权益类产品数量
      portfolioNum: 0, // 模拟组合数量
      modalTitle: '', // 模拟组合模态框title
      simulateObj: {}, //编辑\详情模拟组合数据
      selectName: '', // 选中组合的名称
      selectCode: '', // 选中组合的code
      benchMark: [], // 业绩基准
      initDataSource: [],
    };
    // 绑定lodash的防抖函数，避免频繁搜索的情况
    this.searchOnChange = debounce(this.searchOnChange, 500);
  }
  componentDidMount() {
    this.props.onRef(this);
    this.getbenchMarkData();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const thisPortfolioCode = this.props.workStationM.CombinationType?.portfolioCode;
    const nextPortfolioCode = nextProps.workStationM.CombinationType?.portfolioCode;

    // 清除持仓交易管理卡片组合选项后 行选中状态取消
    if (thisPortfolioCode != nextPortfolioCode) {
      this.setState({
        selectCode: nextPortfolioCode,
      });
    }
    const { state } = this.props;
    const portfolioList = nextProps.workStationM.portfolioList;
    if (nextProps.state !== state) {
      this.setState({
        state: nextProps.state,
      });
    }
    if (JSON.stringify(portfolioList) != JSON.stringify(this.state.portfolioList)) {
      let count1 = 0;
      let count2 = 0;
      portfolioList &&
        portfolioList.map((item) => {
          if (item.portfolioType == '1') count1++;
          if (item.portfolioType == '2') count2++;
        });
      this.setState({
        productNum: count1,
        portfolioNum: count2,
        portfolioList: portfolioList,
        dataSource: portfolioList,
        initDataSource: _.cloneDeep(portfolioList),
      });
    }
    if (nextProps.state == 2 || nextProps.state == 4 || nextProps.state == 15 || nextProps.state == 16) {
      this.setState({
        showContent: true,
      });
    } else {
      this.setState({
        showContent: false,
      });
    }
  }

  // 刷新列表数据源
  refresh = () => {
    this.props.form.setFieldsValue({
      portfolio: '',
    });
    this.props.dispatch({
      type: 'workStationM/queryProductTableList',
      payload: {},
      callback: (data) => {
        this.setState({
          dataSource: data,
        });
      },
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          key: 'operate',
          type: 'operate',
          title: '操作',
          width: 150,
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                if (record.portfolioType == '2') {
                  this.setState({
                    showModal: true,
                    modalTitle: '编辑',
                    simulateObj: record,
                  });
                } else {
                  this.props.changePage(2);
                  this.props.jumpProductPage('edit', record.id);
                }
              },
            },
            {
              title: '详情',
              onClick: (record, index) => {
                if (record.portfolioType == '2') {
                  this.setState({
                    showModal: true,
                    modalTitle: '详情',
                    simulateObj: record,
                  });
                } else {
                  this.props.changePage(2);
                  this.props.jumpProductPage('view', record.id);
                }
              },
            },
            {
              title: '删除',
              rules: {
                disabled: { items: [{ key: 'portfolioType', value: ['1'], relation: ['='] }] },
              },
              onClick: (record, index) => {
                this.props.dispatch({
                  type: 'barraProductM/deletePortfolio',
                  payload: {
                    portfolioId: record.portfolioId,
                  },
                  callback: () => {
                    this.refresh();
                    this.props.changePortfolio(record);
                    this.props.productOnChange(record.portfolioCode, 1);
                  },
                });
              },
            },
          ],
        });
      }
    }
    return data;
  };

  // 表格行点击事件
  selectRow = (record, index) => {
    // 设置组合类型
    this.props.dispatch({
      type: 'workStationM/setState',
      payload: {
        CombinationType: {
          portfolioType: record.portfolioType,
          portfolioTypeDes: record.portfolioType == 1 ? '真实' : record.portfolioType == 2 ? '模拟' : '',
          productId: record.id,
          portfolioCode: record.portfolioCode,
          portfolioId: record.portfolioId,
        },
      },
    });

    this.setState(
      {
        activeIndex: index, //获取点击行的索引
        selectName: record.portfolioName,
        selectCode: record.portfolioCode,
      },
      () => {
        this.props.changePortfolio(record);
        this.props.selectedOnChange(record.portfolioCode);
      },
    );
  };

  // 表格高亮行
  setClassName = (record, index) => {
    return record.portfolioCode === this.state.selectCode ? 'selectRow' : '';
  };

  onExpendClick = (e) => {
    this.setState(
      {
        showContent: e,
      },
      () => {
        this.props.stateOnChange(e ? 1 : 2);
      },
    );
  };

  // 新增模拟组合确认
  handleOk = () => {
    const { dispatch } = this.props;
    let values = this.state.formRef.getFormGroupData();
    if (values) {
      values.establishTime = moment(values.establishTime).format('YYYY-MM-DD');
      if (this.state.modalTitle.indexOf('新增') != -1) {
        dispatch({
          type: 'barraProductM/addPortfolio',
          payload: values,
          callback: () => {
            this.setState({
              showModal: false,
            });
            this.refresh();
            this.props.changePortfolio();
            this.props.productOnChange('', 0);
          },
        });
      } else {
        dispatch({
          type: 'barraProductM/editPortfolio',
          payload: {
            portfolioId: this.state.simulateObj.portfolioId,
            ...values,
          },
          callback: () => {
            this.setState({
              showModal: false,
            });
            this.refresh();
            this.props.changePortfolio(this.state.simulateObj);
            this.props.productOnChange(this.state.simulateObj.portfolioCode, 2);
          },
        });
      }
    }
  };

  handleCancel = () => {
    this.setState({
      showModal: false,
    });
  };

  // 业绩基准模糊搜索
  getbenchMarkData = (e) => {
    const { dispatch } = this.props;
    this.setState({
      benchMark: [],
    });
    dispatch({
      type: 'barraProductM/getPerformanceBenchmarks',
      payload: {},
      callback: (res) => {
        // console.log(res);
        if (res.dataSource && res.dataSource.length) {
          let arr = [];
          res.dataSource.map((item) => {
            arr.push({ title: item.title, value: item.value });
          });
          this.setState({
            benchMark: arr,
          });
        }
      },
    });
  };

  // 新增模态框
  showModal = () => {
    const { showModal, modalTitle, simulateObj, benchMark } = this.state;
    const { loading } = this.props;
    const modalProps =
      modalTitle == '详情'
        ? {
            footer: null,
            visible: showModal,
            title: modalTitle,
            width: 350,
            confirmLoading: loading.effects['barraProductM/addPortfolio'] === true || loading.effects['barraProductM/editPortfolio'] === true,
          }
        : {
            visible: showModal,
            title: modalTitle,
            width: 350,
            confirmLoading: loading.effects['barraProductM/addPortfolio'] === true || loading.effects['barraProductM/editPortfolio'] === true,
          };
    const formGroupProps = {
      onRef: (ref) => {
        this.state.formRef = ref;
      },
      form: this.props.form,
      autoLayout: false,
      dataSource: [
        {
          span: 24,
          dataIndex: 'portfolioName',
          type: DATA_ENTRY.INPUT,
          title: '组合名称',
          initialValue: simulateObj.portfolioName,
          placeholder: '请输入',
          disabled: modalTitle == '详情',
          max: 100,
          rules: [{ required: true, message: '请输入组合名称!' }],
          controlLabelSpan: 8,
        },
        {
          span: 24,
          dataIndex: 'initialAsset',
          title: '初始资金',
          type: DATA_ENTRY.INPUTNUMBER,
          unit: '元',
          initialValue: simulateObj.initialAsset,
          disabled: modalTitle == '详情' || modalTitle == '编辑',
          splitStyle: true,
          precision: 2,
          rules: [{ required: true, message: '请输入初始资金!' }],
          min: 0.01,
          max: 99999999999,
        },
        {
          span: 24,
          dataIndex: 'performanceBenchmarkId',
          title: '业绩基准',
          type: DATA_ENTRY.SELECT,
          positionBody: true,
          initialValue: simulateObj.performanceBenchmarkId,
          disabled: modalTitle == '详情',
          dataSource: benchMark,
          onSearch: (e) => {
            this.getbenchMarkData(e);
          },
          // filterOption: (input, option) => option.props.children.indexOf(input) > -1,
          rules: [{ required: true, message: '请选择业绩基准!' }],
        },
        {
          span: 24,
          dataIndex: 'establishTime',
          title: '组合起始日',
          type: DATA_ENTRY.SINGLEDATE,
          disabled: modalTitle == '详情' || modalTitle == '编辑',
          initialValue: simulateObj.establishTime ? moment(simulateObj.establishTime) : moment(),
          rules: [{ required: true, message: '请选择日期!' }],
          disableEnd: moment().add(1, 'day'),
        },
      ],
    };
    return (
      <ModalC {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel}>
        <FormGroup {...formGroupProps} />
      </ModalC>
    );
  };

  // 搜索框图标
  rightContent = () => {
    return (
      <div className='flotRight'>
        <img src={search}></img>
      </div>
    );
  };

  // 响应搜索框变化
  searchOnChange = (e) => {
    const { portfolioList } = this.state;
    let newListDataSource = [];
    let searchData = e.target?.value;
    if (searchData == '' || searchData == null) {
      newListDataSource = portfolioList;
    } else {
      newListDataSource = portfolioList.filter((item) => {
        return item.portfolioName.toString().includes(searchData) || item.portfolioCode.toString().includes(searchData);
      });
    }
    this.setState({ dataSource: newListDataSource });
  };

  render() {
    const { columns, dataSource, state, showModal, showContent, productNum, portfolioNum, selectName, initDataSource } = this.state;
    const { loading } = this.props;
    const newColumns = this.changeColumns(columns);
    return (
      <div className={styles.mainCont}>
        {!initDataSource?.length ? (
          <div className={styles.noproduct}>
            <img src={pic} />
            <div className={styles.text}>暂无产品组合相关数据，请新增产品或模拟组</div>
            <div>
              <PrimaryC
                title={'新增产品'}
                onClick={() => {
                  this.props.changePage(2);
                  this.props.jumpProductPage('add', '');
                }}
                style={{ marginRight: '16px' }}
              />
              <PrimaryC
                title={'新增模拟组合'}
                onClick={() => {
                  this.setState({
                    showModal: true,
                    modalTitle: '新增模拟组合',
                    simulateObj: {},
                  });
                }}
              />
            </div>
          </div>
        ) : showContent ? (
          <div className={styles.openCont}>
            {/* 展开 */}
            <CardC title='产品组合' titleTip={`共${productNum}只权益类产品，${portfolioNum}只模拟组合`} type='1' showContent={true} onExpendClick={this.onExpendClick} />
            <div className={styles.searchCont}>
              <InputC
                form={this.props.form}
                dataIndex='portfolio'
                placeholder='请输入组合名称进行查询'
                suffix={this.rightContent()}
                onChange={(e) => {
                  e.persist(); //以异步方式访问事件属性，调用 event.persist()，阻止react合成事件，允许保留对事件的引用。
                  this.searchOnChange(e);
                }}
                style={{ width: '208px' }}
              />
              <div>
                <PrimaryC
                  title={'新增产品'}
                  onClick={() => {
                    this.props.changePage(2);
                    this.props.jumpProductPage('add', '');
                  }}
                  style={{ marginRight: '16px' }}
                />
                <PrimaryC
                  title={'新增模拟组合'}
                  onClick={() => {
                    this.setState({
                      showModal: true,
                      modalTitle: '新增模拟组合',
                      simulateObj: {},
                    });
                  }}
                />
              </div>
            </div>
            <div className={styles.table}>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                rowClassName={this.setClassName} //表格行点击高亮
                // onRow={(record, index) => ({
                // 	onDoubleClick: () => {
                // 		this.selectRow(record, index);
                // 	},
                // })}
                rowKey='Name'
                hidePage={true}
                loading={loading.effects['workStationM/queryProductTableList']}
                scroll={{ x: 1192, y: 390 }}
              ></TableC>
            </div>
          </div>
        ) : (
          <div className={styles.closeCont} style={{ overflow: 'hidden' }}>
            <CardC title='产品组合' type='1' onExpendClick={this.onExpendClick} showContent={false} />
            {(state == 1 || state == 3 || state == 13 || state == 14) && (
              <div className={styles.content}>
                <div>
                  共<span className={styles.num}> {productNum} </span>只权益类产品，<span className={styles.num}> {portfolioNum} </span>只模拟组合
                </div>
                <div>{selectName ? '当前选中的产品/组合为' : '当前未选择产品/组合'}</div>
                {selectName ? <div className={styles.name}>{selectName}</div> : ''}
              </div>
            )}
            {(state == 11 || state == 12) && (
              <div className={styles.content}>
                <div>
                  共<span className={styles.num}> {productNum} </span>只权益类产品
                </div>
                <div>
                  <span className={styles.num}> {portfolioNum} </span>只模拟组合
                </div>
                <div>{selectName ? '当前选中的产品/组合为' : '当前未选择产品/组合'}</div>
                {selectName ? <div className={styles.name}>{selectName}</div> : ''}
              </div>
            )}
            <div className={styles.closeContbg}>
              <img src={url} />
            </div>
          </div>
        )}
        {showModal ? <div className={styles.modal}>{this.showModal()}</div> : null}
      </div>
    );
  }
}
